package com.zd.config.security;

import com.zd.entity.Admin;
import com.zd.entity.Student;
import com.zd.entity.User;
import com.zd.service.IAdminService;
import com.zd.service.IStudentService;
import com.zd.service.IUserService;
import com.zd.utils.JwtAuthenticationTokenFilter;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author TSP
 * @Date 2021/8/22 20:37
 * @ClassName SecurityConfig
 * @Description ：
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IAdminService adminService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ResultAccessDeniedHandler resultAccessDeniedHandler;

    @Autowired
    private ResultAuthenticationEntryPoint resultAuthenticationEntryPoint;

    @Override
    public void configure(WebSecurity web) throws Exception {
        //设置一些放行的一些路径，不走拦截链
        web.ignoring().antMatchers(
                "/websocket/**",
                "/**.html",
                "/login",
                "/logout/**",
                "/css/**",
                "/js/**",
                "favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/captcha",
                "/admin/**",//放行admin便于测试
                "/grade/basic",
                "/line",
                "/user/**",
                "/**"//测试时全部放行
        );
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            User user = userService.getUserByUserName(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户名或密码不正确");
            }
            return user;
        };
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用JWT，不需要CSRF
        http.csrf().disable()
                //禁用session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //放行(登录及登出)
//                .antMatchers("/login/**", "/logout/**")
//                .permitAll()
                .anyRequest()
                .authenticated()
//                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
//                    @Override
//                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
//                        object.setSecurityMetadataSource(customFilter);
//                        object.setAccessDecisionManager(customUrlAccessDecisionManager);
//                        return object;
//                    }
//                })
                .and()
                //禁用缓存
                .headers()
                .cacheControl();
        //JWT登录拦截器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //自定义异常返回结果(未登录，未授权)
        http.exceptionHandling()
                .accessDeniedHandler(resultAccessDeniedHandler)
                .authenticationEntryPoint(resultAuthenticationEntryPoint);

    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
